<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_services_MediaService extends f_core_Service
{
	/**
	 * @var m_medias_services_MediaService
	 */
	private static $instance;
	
	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}
	
	/**
	 * @return m_medias_services_MediaService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	public function getMediasByFolderId($folderId, $folderLang, $onlyPublished = true)
	{
		$relManager = f_relation_Manager::getInstance();
		
		return $relManager->getChildsByDocType($folderId, array("modules_medias/media"), $folderLang, array("relation_order" => "ASC"), "PUBLISHED");
	}
    
    public function getBgColor($stringBgColor = "000000")
    {
        $bgColor = array();

        for($i = 0; $i < 3; $i++)
        {
            $bgColor[] = substr($stringBgColor, $i*2, 2);
        }

        return $bgColor;
    }

    public function getIconPath($name)
    {
        $conf = f_loader_Config::getInstance()->getParameters("default");
        $theme = $conf['backTheme'];
        $size = "1616";
        $context = "backend";
        $default_path = "%s/themes/%s/%s/medias/icons/%s/%s";

        return sprintf($default_path, URL_RELATIVE, $theme, $context, $size, $name);
    }

    public static function getModuleMediaPath($moduleName, $mediaName)
    {
        return URL_RELATIVE.'/bo'.f_core_Routing::getUrl('moduleMedia', array('moduleName' => $moduleName, 'mediaName' => $mediaName));
    }

    public static function getFolderRealPath($folder)
    {
        $parents = f_relation_Manager::getInstance()->getParentsIdsByDocType($folder->getUniqueId(), "modules_backoffice/folder", $folder->getLang());

        if(!is_array($parents))
        {
            $parents = array();
        }
        else
        {
            foreach($parents as $parent)
            {
                $result[] = $parent['parent_id'];
            }

            $parents = $result;
        }

        array_push($parents, $folder->getUniqueId());
        array_push($parents, strtolower($folder->getLang()));

        $parents = join(DIRECTORY_SEPARATOR, $parents);

        $destPath = HTTP_DIR.DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR.$parents.DIRECTORY_SEPARATOR;
        return $destPath;
    }

    private static function saveMedia($filePath, $fileName, $folder)
    {
        $media = m_medias_documents_Media::createNew();

        $fileObj = f_file_File::getInstance($filePath.$fileName);

        $media	->setMime($fileObj->getMimeType())
                ->setAuthor("pagizer")
                ->setExt($fileObj->getExtension())
                ->setLabel($fileName)
                ->setAlt($fileObj->getFileName())
                ->setTitle($fileObj->getFileName())
                ->save(false);

        $folder->addMedia($media)->save(false);

        if($media->isImage())
        {
            $media->createIcon();
            $media->createMceIcon();
            $media->createPreview();

            $parameters = m_medias_services_ParameterService::getInstance()->getParametersByFolderId($folder->getUniqueId(), $folder->getLang());

            if(!is_null($parameters))
            {
                /* @var $parameter m_medias_documents_Parameter */
                foreach($parameters as $parameter)
                {
                    if($parameter->isGenerateOnUpload())
                    {
                        $media->advancedResizePicture($parameter->getWidth(), $parameter->getHeight(), $parameter->getCrop());
                    }
                }
            }
        }

        return $media;
    }

    /**
     * Download a distant picture into a media folder
     *
     * @param string $src
     * @return m_medias_documents_Media
     */
    public static function downloadDistantMedia($src)
    {
        $mime  = array( 'image/gif' => 'gif',
                        'image/jpeg' => 'jpeg',
                        'image/png' => 'png',
                        'application/x-shockwave-flash' => 'swf',
                        'image/psd' => 'psd',
                        'image/bmp' => 'bmp',
                        'image/tiff' => 'tiff',
                        'image/tiff' => 'tiff',
                        'image/jp2' => 'jp2',
                        'image/iff' => 'iff',
                        'image/vnd.wap.wbmp' => 'bmp',
                        'image/xbm' => 'xbm',
                        'image/vnd.microsoft.icon' => 'ico');

        $mediasRootNode = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode('medias');
        $folder = f_target_Manager::getDocumentByUniqueTarget('downloadFolder', $mediasRootNode->getUniqueId());
        $media = null;

        if(!is_object($folder))
        {
           $folder = f_document_Provider::getInstance()->createNewDocument('modules_backoffice/folder');
           $folder->setLabel('Download')->setModule('medias')->save();

           $mediasRootNode->addFolder($folder)->save();
           f_target_Manager::getInstance()->setModule('medias')->setDocument($folder)->setTarget('downloadFolder')->save();
        }

        $exp = explode('/', $src);
        $fileName = end($exp);

            $distContent = file_get_contents($src);

            $destDir = self::getFolderRealPath($folder);

            if(!is_dir($destDir))
            {
                mkdir($destDir, 0777, true);
            }

            file_put_contents($destDir.$fileName, $distContent);

            $finfo = getimagesize($destDir.$fileName);

            if(!empty($finfo))
            {
                $ext = strtolower(substr(strrchr($destDir.$fileName, "."), 1));
                $fMime = $finfo['mime'];

                $extension = ($mime[$fMime] == 'jpeg') ? 'jpg' : $mime[$fMime];

                if($ext != $extension)
                {
                    $newFileName = str_replace('.', '', $fileName);
                    $newFileName = floor(microtime(true)).'.'.$extension;
                    rename($destDir.$fileName, $destDir.$newFileName);
                    $fileName = $newFileName;
                }

                $media = self::saveMedia($destDir, $fileName, $folder);
            }
            else
            {
                unlink($destDir.$fileName);
            }


        return $media;
    }
}